package fr.uvsq.isty.bdh.hchess.ics;

import ictk.boardgame.chess.net.ics.ICSProtocolHandler;
import ictk.boardgame.chess.net.ics.event.ICSConnectionEvent;
import ictk.boardgame.chess.net.ics.fics.FICSProtocolHandler;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Florent Hemmi <florent.hemmi@gmail.com>
 */
public class ICSclient {
    
    public static final int FICS = 1;
    public static final int ICC = 2;
    
    private static final String DEFAULT_HOST = "freechess.org";
    private static final int DEFAULT_PORT = 5000;
    
    private ICSProtocolHandler ics;
    
    private int protocol;
    private String host;
    private String user;
    private String pass;
    private int port;
    
    public ICSclient(int protocol, String host, String user, String pass, int port) throws ProtocolException {
        if (protocol != FICS) {
            throw new ProtocolException("Protocol not yet supported.");
        }
        this.protocol = protocol;
        this.host = host;
        this.user = user;
        this.pass = pass;
        this.port = port;
        
        ics = new FICSProtocolHandler(host, port);
    }
    
    public void connect() {
        if (!ics.isConnected()) {
            try {
                System.out.println("[Client] Trying to connect to \""+host+
                        "\" on port "+port+"...");
                ics.setHandle(user+"\n");
                ics.setPassword(pass+"\n");
                ics.connect();
            } catch (UnknownHostException ex) {
                Logger.getLogger(ICSclient.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(ICSclient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public void disconnect() {
        ics.disconnect();
    }
    
    public boolean isLoggedIn() {
        return ics.isLoggedIn();
    }
    
    public void sendCommand(String cmd) {
        ics.sendCommand(cmd, true);
    }

    public void connectionStatusChanged(ICSConnectionEvent evt) {
        ICSProtocolHandler conn = evt.getConnection();

       if (!conn.isConnected()) {
          System.err.println("Connection Terminated: " + new Date());
          System.exit(0);
       }
       else {
          System.err.println("Connection Live but received event: " + evt);
       }
    }
}
